package com.cos.utils.bucket;

import com.cos.config.COSConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.CreateBucketRequest;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author Irving
 * @create 2021/7/14
 * @desc 对Bucket的操作
 **/
public class COSBucketUtil {

    /**
     * 配置对象,用于获取cosClient
     */
    private COSConfig cosConfig;
    /**
     * cosClient
     */
    private COSClient cosClient;

    {
        this.cosConfig = new COSConfig();
        this.cosClient = cosConfig.getCosClient();
    }

    /**
     * 得到所有 bucket
     *
     * @return buckets
     */
    public List<Bucket> bucket() {
        return cosClient.listBuckets();
    }

    /**
     * 创建bucket
     *
     * @param bucketName              bucket名
     * @param cannedAccessControlList 权限
     * @return 返回创建的bucket
     */
    public Bucket create(StringBuffer bucketName, CannedAccessControlList cannedAccessControlList) {
        CreateBucketRequest createBucketRequest = new CreateBucketRequest(cosConfig.generateBucketId(bucketName).toString());
        // 设置 bucket 的权限为 Private(私有读写), 其他可选有公有读私有写, 公有读写
        createBucketRequest.setCannedAcl(cannedAccessControlList);
        return cosClient.createBucket(createBucketRequest);
    }

    /**
     * 当前桶是否存在或者是否有权限访问
     *
     * @param bucketName 存储桶
     * @return true false
     */
    public boolean doesBucketExist(String bucketName) {
        return cosClient.doesBucketExist(bucketName);
    }

    /**
     * 删除空桶
     *
     * @param bucketName 存储桶
     */
    public void delete(String bucketName) {
        cosClient.deleteBucket(bucketName);
    }

    /**
     * 关闭资源
     */
    public void close() {
        //帮助gc回收
        cosConfig = null;
        if (cosClient != null) {
            cosClient.shutdown();
            cosClient = null;
        }
    }
}
